package com.qf.qfleadnewscommons.minio;

import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

public class MinioOperator {

    private MinioClient minioClient;
    private MinioProperties properties;

    public MinioOperator(MinioClient minioClient, MinioProperties properties) {
        this.minioClient = minioClient;
        this.properties = properties;
    }

    public String uploadImage(InputStream fis) throws Exception {

        //① 目录分离 ② 文件重名
        String filename = UUID.randomUUID().toString() + ".jpg";

        //构建一个目录分离的路径
        filename = buildPath(filename);

        try {
            //生成唯一文件名
            //上传对象的方法
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(properties.getBucket())
                            .object(filename)
                            .contentType("image/jpeg")
                            .stream(fis, fis.available(), -1)
                            .build());

        }finally {
            fis.close();
        }

        String url = properties.getEndpoint() + "/"+ properties.getBucket() + "/" + filename;

        return url;
    }

    public String uploadHtml(InputStream fis) throws Exception {

        //① 目录分离 ② 文件重名
        String filename = UUID.randomUUID().toString() + ".html";

        //构建一个目录分离的路径
        filename = buildPath(filename);

        try {
            //生成唯一文件名
            //上传对象的方法
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(properties.getBucket())
                            .object(filename)
                            .contentType("text/html")
                            .stream(fis, fis.available(), -1)
                            .build());

        }finally {
            fis.close();
        }

        String url = properties.getEndpoint() + "/"+ properties.getBucket() + "/" + filename;

        return url;
    }

    /**
     * 根据url下载图片
     * @param pathUrl : http://localhost:9005/leadnews/2023/04/11/57104e33-1f10-4356-b8db-43934ff2a2d6.jpg
     *                  leadnews/2023/04/11/57104e33-1f10-4356-b8db-43934ff2a2d6.jpg
     * @return
     */
    public byte[] downLoadFile(String pathUrl)  {
        String key = pathUrl.replace(properties.getEndpoint()+"/","");
        int index = key.indexOf("/");
        String bucket = key.substring(0,index); // leadnews
        String filePath = key.substring(index+1); // 2023/04/11/57104e33-1f10-4356-b8db-43934ff2a2d6.jpg
        InputStream inputStream = null;
        try {
            inputStream = minioClient.getObject(GetObjectArgs.builder().bucket(properties.getBucket()).object(filePath).build());
        } catch (Exception e) {
            e.printStackTrace();
        }

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while (true) {
            try {
                if (!((rc = inputStream.read(buff, 0, 100)) > 0)) break;
            } catch (IOException e) {
                e.printStackTrace();
            }
            byteArrayOutputStream.write(buff, 0, rc);
        }
        return byteArrayOutputStream.toByteArray();
    }

    /**
     * 根据日期，生成多级目录
     * 2023-4-7 ---->  2023/04/07/xxx.jpg
     *
     *  filename -- 2df34ff33433kfd323 --
     *      filename.charAt(0) - 2
     *      filename.charAt(1) - d
     *      filename.charAt(2) - f
     *      filename.charAt(3) - f
     *       .....
     *
     *      ====> 2/d/f   每一级有10+26=36种可能
     *          3级目录有 36*36*36 = 46000
     *
     * @param filename
     * @return
     */
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
    private String buildPath(String filename) {
        String dir = sdf.format(new Date());
        return dir + "/" +  filename;
    }
}
